package com.h2cloud.JUCTest.CountDownLatch;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @Package: com.h2cloud.JUCTest.mianShiTi
 * @ClassName: a1
 * @Author: h2cloud
 * @CreateTime: 2022/9/25 11:18 上午
 * @Description:
 */

/**
 * 必须先让t2先进行启动 使用wait 和 notify 进行相互通讯，wait会释放锁，notify不会释放锁
 */
@Slf4j
public class A1 {
	volatile List list = new ArrayList();

	public void add(int i) {
		list.add(i);
	}

	public int getSize() {
		return list.size();
	}

	public static void main(String[] args) {
		A1 a1 = new A1();
		Object lock = new Object();
		new Thread(() -> {
			synchronized (lock) {
				if (a1.getSize() != 5) {
					try {
						lock.wait();
						log.info("getSize == 5");
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				lock.notifyAll();
			}
		}, "t1").start();

		new Thread(() -> {
			synchronized (lock) {
				for (int i = 0; i < 10; i++) {
					a1.add(i);
					log.info("add " + i);
					if (a1.getSize() == 5) {
						lock.notifyAll();
						try {
							lock.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}, "t2").start();
	}
}
